﻿using System;

using VirtualTournaments.DataAccess.SqlServer.DataProxies;

namespace VirtualTournaments.DataAccess.SqlServer.DataMappers
{
	internal sealed class BetsDataMapper : AbstractDataMapper<SqlServer.Bet, Business.Bets.Bet, DataProxies.BetDataProxy>
	{
		#region Singleton implementation

		private static BetsDataMapper _instance = null;
		private static object _instanceLocker = new object();

		private BetsDataMapper() { }

		public static BetsDataMapper Instance
		{
			get
			{
				if (_instance == null)
				{
					lock (_instanceLocker)
					{
						if (_instance == null)
						{
							_instance = new BetsDataMapper();
						}
					}
				}
				return _instance;
			}
		}

		#endregion

		internal override VirtualTournamentsDataContext GetDataContext()
		{
			return VirtualTournamentsDataContext.Instance;
		}

		internal override System.Data.Linq.Table<Bet> GetDataTable()
		{
			return GetDataContext().Bets;
		}

		internal override Business.Bets.Bet DataObject2BusinessObject(SqlServer.Bet dataObject)
		{
			return new BetDataProxy(dataObject);
		}

		internal override void BusinessObject2DataObject(Business.Bets.Bet bizBet, SqlServer.Bet dataBet)
		{
			if (bizBet.Bettor != null)
			{
				SqlServer.User dataUser = UsersDataMapper.Instance.GetOneAsDataObject(user => user.UserName == bizBet.Bettor.UserName);
				if (dataUser != null)
					dataBet.BettorUser = dataUser;
				else
					dataBet.BettorUser = UsersDataMapper.Instance.Save(bizBet.Bettor);
			}
			dataBet.WageredMoney = bizBet.WageredMoney;
			dataBet.Odds = Convert.ToDouble(bizBet.Odds);
		}

		internal override void DataProxy2DataObject(BetDataProxy proxyBet, SqlServer.Bet dataBet)
		{
			//TODO: untested
			if (proxyBet.BettorHasBeenRead)
			{
				SqlServer.User dataUser = UsersDataMapper.Instance.GetOneAsDataObject(user => user.UserName == proxyBet.Bettor.UserName);
				if (dataUser != null)
					dataBet.BettorUser = dataUser;
				else
					dataBet.BettorUser = UsersDataMapper.Instance.Save(proxyBet.Bettor);
			}
			dataBet.WageredMoney = proxyBet.WageredMoney;
			dataBet.Odds = Convert.ToDouble(proxyBet.Odds);
		}
	}
}
